<!doctype html><html lang dir=ltr><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>【第5周程序】函数和代码复用 | Python | Hui.Ke - Blog</title><meta name=generator content="Hugo Eureka 0.9.3"><link rel=stylesheet href=https://b.hui.ke/css/eureka.min.9cec6350e37e534b0338fa9a085bf06855de3b0f2dcf857e792e5e97b07ea905d4d5513db554cbc26a9c3da622bae92d.css><script defer src=https://b.hui.ke/js/eureka.min.fa9a6bf6d7a50bb635b4cca7d2ba5cf3dfb095ae3798773f1328f7950028b48c17d06276594e1b5f244a25a6c969a705.js></script>
<link rel=preconnect href=https://fonts.googleapis.com><link rel=preconnect href=https://fonts.gstatic.com crossorigin><link rel=preload href="https://fonts.googleapis.com/css2?family=Lora:wght@400;600;700&family=Noto+Serif+SC:wght@400;600;700&display=swap" as=style onload='this.onload=null,this.rel="stylesheet"'><link rel=stylesheet href=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/styles/vs.min.css media=print onload='this.media="all",this.onload=null' crossorigin><script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/highlight.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/bash.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/ini.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/json.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/php.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/python.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/shell.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/sql.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/x86asm.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/xml.min.js crossorigin></script>
<link rel=stylesheet href=https://b.hui.ke/css/highlightjs.min.2958991528e43eb6fc9b8c4f2b8e052f79c4010718e1d1e888a777620e9ee63021c2c57ec7417a3108019bb8c41943e6.css media=print onload='this.media="all",this.onload=null'><script defer type=text/javascript src=https://lib.baomitu.com/font-awesome/6.1.1/js/all.min.js></script>
<link rel=stylesheet href=https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.css integrity=sha384-MlJdn/WNKDGXveldHDdyRP1R4CTHr3FeuDNfhsLPYrq2t0UBkUdK2jyTnXPEK1NQ media=print onload='this.media="all",this.onload=null' crossorigin><script defer src=https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.js integrity=sha384-VQ8d8WVFw0yHhCk5E8I86oOhv48xLpnDZx5T9GogA/Y84DcCKWXDmSDfn13bzFZY crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/contrib/auto-render.min.js integrity=sha384-+XBljXPPiv+OzfbB3cVmLHf4hdUFHlWNZN5spNQ7rmHTXpd7WvJum6fIACpNNfIR crossorigin></script>
<script>document.addEventListener("DOMContentLoaded",function(){renderMathInElement(document.body,{delimiters:[{left:"$$",right:"$$",display:!0},{left:"$",right:"$",display:!1},{left:"\\(",right:"\\)",display:!1},{left:"\\[",right:"\\]",display:!0}]})})</script><script defer src=https://cdn.jsdelivr.net/npm/mermaid@8.14.0/dist/mermaid.min.js integrity=sha384-atOyb0FxAgN9LyAc6PEf9BjgwLISyansgdH8/VXQH8p2o5vfrRgmGIJ2Sg22L0A0 crossorigin></script>
<link rel=icon type=image/png sizes=32x32 href=https://b.hui.ke/icon_hub7ca0b5404c6d576559b2bd22c64b0e5_2009_32x32_fill_box_center_3.png><link rel=apple-touch-icon sizes=180x180 href=https://b.hui.ke/icon_hub7ca0b5404c6d576559b2bd22c64b0e5_2009_180x180_fill_box_center_3.png><meta name=description content="  程序设计练习题和考试题"><script type=application/ld+json>{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Docs","item":"https://b.hui.ke/docs/"},{"@type":"ListItem","position":2,"name":"Python","item":"https://b.hui.ke/docs/python/"},{"@type":"ListItem","position":3,"name":"【第5周程序】函数和代码复用","item":"https://b.hui.ke/docs/python/15/"}]}</script><script type=application/ld+json>{"@context":"https://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://b.hui.ke/docs/python/15/"},"headline":"【第5周程序】函数和代码复用 | Python | Hui.Ke - Blog","datePublished":"2022-04-11T15:53:42+08:00","dateModified":"2022-04-11T15:53:42+08:00","wordCount":1553,"author":{"@type":"Person","name":"Hui.Ke"},"publisher":{"@type":"Person","name":"Hui.Ke","logo":{"@type":"ImageObject","url":"https://b.hui.ke/icon.png"}},"description":"\u003cp\u003e  程序设计练习题和考试题\u003c\/p\u003e"}</script><meta property="og:title" content="【第5周程序】函数和代码复用 | Python | Hui.Ke - Blog"><meta property="og:type" content="article"><meta property="og:image" content="https://b.hui.ke/icon.png"><meta property="og:url" content="https://b.hui.ke/docs/python/15/"><meta property="og:description" content="  程序设计练习题和考试题"><meta property="og:site_name" content="Hui.Ke - Blog"><meta property="article:published_time" content="2022-04-11T15:53:42+08:00"><meta property="article:modified_time" content="2022-04-11T15:53:42+08:00"><meta property="article:section" content="docs"><meta property="article:tag" content="Program"><meta property="og:see_also" content="https://b.hui.ke/docs/python/20/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/10/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/19/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/9/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/18/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/8/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/17/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/7/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/16/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/6/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/5/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/14/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/4/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/13/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/3/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/12/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/2/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/11/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/1/"><script>!function(e){"use strict";!function(){var i,s=window,o=document,a=e,c="".concat("https:"===o.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=o.createElement("script"),r=o.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",a.d=n,i=function(){s.LA.ids.push(a)},s.LA?s.LA.ids&&i():(s.LA=e,s.LA.ids=[],i()),r.parentNode.insertBefore(n,r)}()}({id:"Jgb8aUbG5e3rqhrs",ck:"Jgb8aUbG5e3rqhrs",autoTrack:!0,hashMode:!0})</script><body class="flex min-h-screen flex-col"><header class="min-h-16 pl-scrollbar bg-secondary-bg fixed z-50 flex w-full items-center shadow-sm"><div class="mx-auto w-full max-w-screen-xl"><script>let storageColorScheme=localStorage.getItem("lightDarkMode");((storageColorScheme=="Auto"||storageColorScheme==null)&&window.matchMedia("(prefers-color-scheme: dark)").matches||storageColorScheme=="Dark")&&document.getElementsByTagName("html")[0].classList.add("dark")</script><nav class="flex items-center justify-between flex-wrap px-4 py-4 md:py-0"><a href=/ class="me-6 text-primary-text text-xl font-bold">Hui.Ke - Blog</a>
<button id=navbar-btn class="md:hidden flex items-center px-3 py-2" aria-label="Open Navbar">
<i class="fas fa-bars"></i></button><div id=target class="hidden block md:flex md:grow md:justify-between md:items-center w-full md:w-auto text-primary-text z-20"><div class="md:flex md:h-16 text-sm md:grow pb-4 md:pb-0 border-b md:border-b-0"><a href=/posts/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Posts</a>
<a href=/docs/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 selected-menu-item me-4">Docs</a>
<a href=/categories/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Categories</a>
<a href=/series/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Series</a>
<a href=/tags/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Tags</a>
<a href=/love/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Love</a>
<a href=/about/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">About</a></div><div class=flex><div class="relative pt-4 md:pt-0"><div class="cursor-pointer hover:text-eureka" id=lightDarkMode><i class="fas fa-adjust"></i></div><div class="fixed hidden inset-0 opacity-0 h-full w-full cursor-default z-30" id=is-open></div><div class="absolute flex flex-col start-0 md:start-auto end-auto md:end-0 hidden bg-secondary-bg w-48 rounded py-2 border border-tertiary-bg cursor-pointer z-40" id=lightDarkOptions><span class="px-4 py-1 hover:text-eureka" name=Light>Light</span>
<span class="px-4 py-1 hover:text-eureka" name=Dark>Dark</span>
<span class="px-4 py-1 hover:text-eureka" name=Auto>Auto</span></div></div></div></div><div class="fixed hidden inset-0 opacity-0 h-full w-full cursor-default z-0" id=is-open-mobile></div></nav><script>let element=document.getElementById("lightDarkMode");storageColorScheme==null||storageColorScheme=="Auto"?document.addEventListener("DOMContentLoaded",()=>{window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",switchDarkMode)}):storageColorScheme=="Light"?(element.firstElementChild.classList.remove("fa-adjust"),element.firstElementChild.setAttribute("data-icon","sun"),element.firstElementChild.classList.add("fa-sun")):storageColorScheme=="Dark"&&(element.firstElementChild.classList.remove("fa-adjust"),element.firstElementChild.setAttribute("data-icon","moon"),element.firstElementChild.classList.add("fa-moon")),document.addEventListener("DOMContentLoaded",()=>{getcolorscheme(),switchBurger()})</script></div></header><main class="grow pt-16"><div class=pl-scrollbar><div class="mx-auto w-full max-w-screen-xl lg:px-4 xl:px-8"><div class=lg:pt-12><div class="flex flex-col md:flex-row bg-secondary-bg rounded"><div class="md:w-1/4 lg:w-1/5 border-e"><div class="sticky top-16 pt-6"><div id=sidebar-title class="md:hidden mx-4 px-2 pt-4 pb-2 md:border-b text-tertiary-text md:text-primary-text"><span class=font-semibold>Table of Contents</span>
<i class='fas fa-caret-right ms-1'></i></div><div id=sidebar-toc class="hidden md:block overflow-y-auto mx-6 md:mx-0 pe-6 pt-2 md:max-h-doc-sidebar bg-primary-bg md:bg-transparent"><div class="flex flex-wrap ms-4 -me-2 p-2 bg-secondary-bg md:bg-primary-bg rounded"><a class=hover:text-eureka href=https://b.hui.ke/docs/python/>Python</a></div><ul class=ps-6><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/20/>期末测验</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/10/>【第9+周笔记】全课程总结与学习展望</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/19/>【第9周程序】计算生态纵览</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/9/>【第9周笔记】计算生态纵览</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/18/>【第8周程序】程序设计方法学</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/8/>【第8周笔记】程序设计方法学</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/17/>【第7周程序】文件和数据格式化</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/7/>【第7周笔记】文件和数据格式化</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/16/>【第6周程序】组合数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/6/>【第6周笔记】组合数据类型</a></div></li><li class=py-2><div><a class="text-eureka hover:text-eureka" href=https://b.hui.ke/docs/python/15/>【第5周程序】函数和代码复用</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/5/>【第5周笔记】函数和代码复用</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/14/>【第4周程序】程序的控制结构</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/4/>【第4周笔记】程序的控制结构</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/13/>【第3周程序】基本数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/3/>【第3周笔记】基本数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/12/>【第2周程序】Python 基本图形绘制</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/2/>【第2周笔记】Python 基本图形绘制</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/11/>【第1周程序】Python 基本语法元素</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/1/>【第1周笔记】Python 基本语法元素</a></div></li></ul></div></div></div><div class="w-full md:w-3/4 lg:w-4/5 pb-8 pt-2 md:pt-8"><div class=flex><div class="w-full lg:w-3/4 px-6"><article class=prose><h1 class=mb-4>【第5周程序】函数和代码复用</h1><div class="text-tertiary-text not-prose mt-2 flex flex-row flex-wrap items-center"><div class="me-6 my-2"><i class="fas fa-calendar me-1"></i>
<span>2022-04-11</span></div><div class="me-6 my-2"><i class="fa-solid fa-pen-to-square me-1"></i>
<span>2022-04-11</span></div><div class="me-6 my-2"><i class="fas fa-clock me-1"></i>
<span>4 min read</span></div><div class="me-6 my-2"><i class="fas fa-folder me-1"></i>
<a href=https://b.hui.ke/categories/it/ class=hover:text-eureka>IT</a></div><div class="me-6 my-2"><i class="fas fa-th-list me-1"></i>
<a href=https://b.hui.ke/series/python/ class=hover:text-eureka>Python</a></div><div class="me-6 my-2"><i class="fa-solid fa-eye me-1"></i>
<span id=busuanzi_value_page_pv><i class="fa fa-spinner fa-spin"></i></span> Hits</div></div><p>  程序设计练习题和考试题</p><h2 id=七段数码管绘制>七段数码管绘制</h2><p>这是"实例"题，与课上讲解实例相同，请作答检验学习效果。</p><p>七段数码管是一种展示数字的有效方式。</p><p>要求如下：</p><ol><li>使用 time 库获得系统当前时间，格式如下：20190411</li><li>绘制对应的七段数码管</li><li>数码管风格不限</li></ol><h3 id=参考答案>参考答案</h3><pre><code class=language-python>import turtle as t
import time
def drawGap(): #绘制数码管间隔
    t.penup()
    t.fd(5)
def drawLine(draw):   #绘制单段数码管
    drawGap()
    t.pendown() if draw else t.penup()
    t.fd(40)
    drawGap()
    t.right(90)
def drawDigit(d): #根据数字绘制七段数码管
    drawLine(True) if d in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,1,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,6,8] else drawLine(False)
    t.left(90)
    drawLine(True) if d in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if d in [0,2,3,5,6,7,8,9] else drawLine(False)
    drawLine(True) if d in [0,1,2,3,4,7,8,9] else drawLine(False)
    t.left(180)
    t.penup()
    t.fd(20)
def drawDate(date):
    t.pencolor(&quot;red&quot;)
    for i in date:
            drawDigit(eval(i))
def main():
    t.setup(800, 350, 200, 200)
    t.penup()
    t.fd(-300)
    t.pensize(5)
    drawDate(time.strftime('%Y%m%d',time.gmtime()))
    t.done()
main()
</code></pre><h3 id=答案解析>答案解析</h3><p>基本思路：</p><ol><li>绘制单个数字对应的码管</li><li>获得当前系统时间，变成字符串，绘制对应的码管</li></ol><p>思维方法：</p><ol><li>模块化思维：确定接口，封装功能</li><li>规则化思维：抽象过程为规则，计算机自动执行</li><li>化繁为简：将大功能变小组合，分而治之</li></ol><h2 id=科赫雪花小包裹>科赫雪花小包裹</h2><p>这是"实例"题，与课上讲解实例相同，请作答检验学习效果。</p><p>科赫曲线，也叫雪花曲线。绘制科赫曲线。</p><h3 id=参考答案-1>参考答案</h3><pre><code class=language-python>import turtle
def koch(size, n):
    if n == 0:
        turtle.fd(size)
    else:
        for angle in [0, 60, -120, 60]:
            turtle.left(angle)
            koch(size/3, n-1)
def main(level):
    turtle.setup(600,600)
    turtle.penup()
    turtle.goto(-200, 100)
    turtle.pendown()
    turtle.pensize(2)
    koch(400,level)     
    turtle.right(120)
    koch(400,level)
    turtle.right(120)
    koch(400,level)
    turtle.hideturtle()
try:
    level = eval(input(&quot;请输入科赫曲线的阶: &quot;))
    main(level)
except:
    print(&quot;输入错误&quot;)
</code></pre><h3 id=答案解析-1>答案解析</h3><p>基本思路：</p><ol><li>递归思想：函数 + 分支</li><li>递归链条：线段的组合</li><li>递归基例：初始线段</li></ol><p>分形几何是一种迭代的图，广泛存在于自然界中，请尝试选择一个新曲线绘制：</p><ol><li>康托尔集、谢宾斯基三角形门格海绵……</li><li>龙形曲线、空间填充科赫……</li><li>函数递归的深入应用 ……</li></ol><h2 id=任意累积>任意累积</h2><p>请根据编程模板补充代码，计算任意个输入数字的乘积。</p><h3 id=参考答案-2>参考答案</h3><pre><code class=language-python>def cmul(a, *b):
    m = a
    for i in b:
        m *= i
    return m
print(eval(&quot;cmul({})&quot;.format(input())))
</code></pre><h3 id=答案解析-2>答案解析</h3><p>该程序需要注意两个内容：</p><ol><li>无限制数量函数定义的方法，其中 b 在函数 cmul 中表达除了 a 之外的所有输入参数；</li><li>以字符串形式调用函数的方法，&ldquo;cmul()&ldquo;与eval() 的组合，提供了很多灵活性。</li></ol><h2 id=斐波那契数列计算>斐波那契数列计算</h2><p>根据编程模板补充代码，计算斐波那契数列的值，具体功能如下：</p><p>获取用户输入整数 N，其中，N 为正整数</p><p>计算斐波那契数列的值</p><p>如果将斐波那契数列表示为 fbi(N)，对于整数 N，值如下：</p><p>fbi(1) 和 fbi(2) 的值是 1，当 N>2 时，fbi(N) = fbi(N-1) + fbi(N-2)</p><p>请采用递归方式编写。</p><h3 id=参考答案-3>参考答案</h3><pre><code class=language-python>def fbi(n):
    if n == 1 or n == 2:
        return 1 
    else:
        return fbi(n-1) + fbi(n-2)
n = eval(input())
print(fbi(n))
</code></pre><h2 id=汉诺塔实践>汉诺塔实践</h2><p>汉诺塔问题大家都清楚，这里不再赘述。</p><p>请补充编程模板中代码，完成如下功能：</p><p>有三个圆柱 A、B、C，初始时 A 上有 N 个圆盘，N 由用户输入给出，最终移动到圆柱 C 上。</p><p>每次移动步骤的表达方式示例如下：[STEP 10] A->C。其中，STEP 是步骤序号，宽度为 4 个字符，右对齐。</p><p>请编写代码，获得输入 N 后，输出汉诺塔移动的步骤。</p><h3 id=参考答案-4>参考答案</h3><pre><code class=language-python>steps = 0
def hanoi(src, des, mid, n):
    global steps
    if n == 1:
        steps += 1
        print(&quot;[STEP{:&gt;4}] {}-&gt;{}&quot;.format(steps, src, des))
    else:
        hanoi(src, mid, des, n-1)
        steps += 1
        print(&quot;[STEP{:&gt;4}] {}-&gt;{}&quot;.format(steps, src, des))        
        hanoi(mid, des, src, n-1)
N = eval(input())
hanoi(&quot;A&quot;, &quot;C&quot;, &quot;B&quot;, N)
</code></pre><h3 id=答案解析-3>答案解析</h3><p>汉诺塔实例十分经典，学习每门语言都要写一遍。</p><p>这个例子要注意：全局变量的使用以及递归的用法。递归用法注意：函数定义 + 分支表示。</p><h2 id=随机密码生成>随机密码生成</h2><p>以整数 17 为随机数种子，获取用户输入整数 N 为长度，产生 3 个长度为 N 位的密码，密码的每位是一个数字。每个密码单独一行输出。</p><p>产生密码采用 random.randint() 函数。</p><h3 id=参考答案-5>参考答案</h3><pre><code class=language-python>import random
def genpwd(length):
    a = 10**(length-1)
    b = 10**length - 1
    return &quot;{}&quot;.format(random.randint(a, b))
length = eval(input())
random.seed(17)
for i in range(3):
    print(genpwd(length))
</code></pre><h3 id=最优解>最优解</h3><pre><code class=language-python>import random
def genpwd(length):
    return random.randint(10**(length-1),10**length-1)
length = eval(input())
random.seed(17)
for i in range(3):
    print(genpwd(length))
</code></pre><h2 id=连续质数计算>连续质数计算</h2><p>获得用户输入数字 N，计算并输出从 N 开始的 5 个质数，单行输出，质数间用逗号 , 分割。</p><p>注意：需要考虑用户输入的数字 N 可能是浮点数，应对输入取整数；最后一个输出后不用逗号。</p><h3 id=参考答案-6>参考答案</h3><pre><code class=language-python>def prime(m):
    for i in range(2,m):
        if m % i == 0:
            return False
    return True

n = eval(input())
a = round(n)
a = a + 1 if a &lt; n else a 
count = 5
while count &gt; 0:
    if prime(a):
        if count &gt; 1:
            print(a,end=',')
        else:
            print(a)
        count -= 1
    a += 1
</code></pre><h3 id=答案解析-4>答案解析</h3><p>这个代码注意：</p><ol><li>需要对输入小数情况进行判断，获取超过该输入的最小整数（这里没用 floor() 函数）；</li><li>对输出格式进行判断，最后一个输出后不增加逗号（这里没用 .join() 方法）。</li></ol></article><div class=my-4><a href=https://b.hui.ke/tags/program/ class="inline-block bg-tertiary-bg text-sm rounded px-3 py-1 my-1 me-2 hover:text-eureka">#Program</a></div><div class=py-2><div class="my-8 flex flex-col items-center md:flex-row"><a href=https://b.hui.ke/authors/hui.ke/ class="md:me-4 text-primary-text h-24 w-24"><img src=https://b.hui.ke/bagua.webp class="bg-primary-bg w-full rounded-full" alt=Avatar></a><div class="mt-4 w-full md:mt-0 md:w-auto"><a href=https://b.hui.ke/authors/hui.ke/ class="mb-2 block border-b pb-1 text-lg font-bold"><h3>Hui.Ke</h3></a><span class="block pb-2">❤ Cyber Security | Safety is a priority.</span>
<a href=mailto:3199731997@qq.com class=me-2><i class="fas fa-envelope"></i></a>
<a href="https://wpa.qq.com/msgrd?v=3&uin=3199731997" class=me-2><i class="fab fa-qq"></i></a>
<a href=/images/aixinxianquan.webp class=me-2><i class="fab fa-weixin"></i></a></div></div></div><div class="-mx-2 mt-4 flex flex-col border-t px-2 pt-4 md:flex-row md:justify-between"><div><span class="text-primary-text block font-bold">Previous</span>
<a href=https://b.hui.ke/docs/python/6/ class=block>【第6周笔记】组合数据类型</a></div><div class="mt-4 md:mt-0 md:text-right"><span class="text-primary-text block font-bold">Next</span>
<a href=https://b.hui.ke/docs/python/5/ class=block>【第5周笔记】函数和代码复用</a></div></div><div id=valine-comments class=mt-4></div><script defer src=https://cdn.jsdelivr.net/npm/valine@1.4.16/dist/Valine.min.js integrity=sha384-e0+DNUCJo75aOAzHQbFWYBCM9/S4f0BhRJXvEgbE3mMS85RM20MSSGStHuNdY2QK crossorigin></script>
<script>document.addEventListener("DOMContentLoaded",function(){new Valine({el:"#valine-comments",appId:"BQnVqWIiq78AdqwyhvBVAa3y-MdYXbMMI",appKey:"RKg5By312YjM8rU6WkkfK9IN",recordIP:"true",serverURLs:"https://l.hui.ke",visitor:"true"})})</script></div><div class="hidden lg:block lg:w-1/4"><div class="bg-secondary-bg
prose sticky top-16 z-10 hidden px-6 py-4 lg:block"><h3>On This Page</h3></div><div class="sticky-toc
border-s
hidden px-6 pb-6 lg:block"><nav id=TableOfContents><ul><li><a href=#七段数码管绘制>七段数码管绘制</a><ul><li><a href=#参考答案>参考答案</a></li><li><a href=#答案解析>答案解析</a></li></ul></li><li><a href=#科赫雪花小包裹>科赫雪花小包裹</a><ul><li><a href=#参考答案-1>参考答案</a></li><li><a href=#答案解析-1>答案解析</a></li></ul></li><li><a href=#任意累积>任意累积</a><ul><li><a href=#参考答案-2>参考答案</a></li><li><a href=#答案解析-2>答案解析</a></li></ul></li><li><a href=#斐波那契数列计算>斐波那契数列计算</a><ul><li><a href=#参考答案-3>参考答案</a></li></ul></li><li><a href=#汉诺塔实践>汉诺塔实践</a><ul><li><a href=#参考答案-4>参考答案</a></li><li><a href=#答案解析-3>答案解析</a></li></ul></li><li><a href=#随机密码生成>随机密码生成</a><ul><li><a href=#参考答案-5>参考答案</a></li><li><a href=#最优解>最优解</a></li></ul></li><li><a href=#连续质数计算>连续质数计算</a><ul><li><a href=#参考答案-6>参考答案</a></li><li><a href=#答案解析-4>答案解析</a></li></ul></li></ul></nav></div><script>window.addEventListener("DOMContentLoaded",()=>{enableStickyToc()})</script></div></div></div></div></div><script>document.addEventListener("DOMContentLoaded",()=>{hljs.highlightAll(),changeSidebarHeight(),switchDocToc()})</script></div></div></main><footer class=pl-scrollbar><div class="mx-auto w-full max-w-screen-xl"><div class="text-center p-6 pin-b"><script async src=/js/click.js></script><div id=poem_ip></div><script type=text/javascript>jinrishici.load(function(e){tags.innerHTML=e.data.matchTags})</script><div><span id=timeDate>载入年天数...</span><span id=times>载入时分秒...</span>
<script async src=/js/duration.js></script></div><a href=https://www.foreverblog.cn/go.html target=_blank><img src=https://img.foreverblog.cn/wormhole_4_tp.gif alt style=display:inline-block;width:auto;height:32px title=穿梭虫洞-随机访问十年之约友链博客></a><p class="text-sm text-tertiary-text"><script async src=//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js></script>本站总访问量 <span id=busuanzi_value_site_pv></span> 次
&#183; 您是本站的第 <span id=busuanzi_value_site_uv></span> 个小伙伴</p><script async src=/js/tab.js></script></div></div></footer></body></html>